/**   使用方法
*	    this.downloadTemplete(
        path + downloadReport,
        'POST',
        this.params,
        1,
        () => {
          this.downloadLoading = false
        }
      )
**/

let index = 0;

export default {
  methods: {
    downloadTemplete(url, method, params, allCount, callBack) {
      let ajax = new XMLHttpRequest();
      let paramStr = '';
      let formData = new FormData();

      if (!params) {
        paramStr = null;
      } else {
        for (let i in params) {
          paramStr += i + '=' + params[i] + '&';
          formData.append(i, params[i]);
        }

        paramStr = paramStr.replace(/&$/gi, '');
      }

      if (method === 'GET') {
        url += '?' + paramStr;
        paramStr = null;
      }

      ajax.open(method, url, true);

      ajax.responseType = 'blob';

      ajax.setRequestHeader(
        'Authorization',
        sessionStorage.getItem('token') || ''
      );
      ajax.setRequestHeader('X-Requested-With', true);

      ajax.send(formData);

      ajax.onreadystatechange = function () {
        if (ajax.readyState == 4) {
          if (ajax.status == 200) {
            let fileName = '下载文件'
            if (ajax.getResponseHeader('content-disposition')) {
              fileName = decodeURI(
                ajax.getResponseHeader('content-disposition').split('=')[1]
              );
            }


            let res = 'response' in ajax ? ajax.response : ajax.responseText;
            var reader = new FileReader();

            reader.readAsDataURL(res); // 转换为base64，可以直接放入a表情href
            reader.onload = function (e) {
              // 转换完成，创建一个a标签用于下载
              var a = document.createElement('a');
              a.download = fileName;
              a.href = e.target.result;
              document.body.append(a); // 修复firefox中无法触发click
              a.click();
              document.body.removeChild(a);
            };

            index++;
            if (index === allCount) {
              callBack();
              index = 0;
            }
          }
        }
      };
    }
  }
};
